<template>
  <div class="goods-base-detail-container">
    <div v-if="pageLoaded" class="register-main">
      <el-form class="el-form--label-left" :label-position="labelPosition" label-width="80px" :model="formData" ref="formData" :rules="formRules">
        <div class="title">
          商品分类
        </div>
        <el-form-item label="商品分类" prop="cateId" label-width="150px">
          <el-cascader :disabled="disabled" v-model="formData.cateArr" :props="props" @change="handleChange" placeholder="请选择商品分类" :clearable="true" :show-all-levels="true"></el-cascader>
        </el-form-item>
        <div class="title">
          基本信息
        </div>
        <el-form-item label="商品名称" prop="name" label-width="150px">
          <el-input :disabled="disabled" v-model="formData.name"></el-input>
        </el-form-item>
        <el-form-item label="商家商品编码" prop="outSerialNo" label-width="150px">
          <el-input :disabled="disabled" v-model="formData.outSerialNo"></el-input>
        </el-form-item>
        <el-form-item label="商品品牌" prop="brandId" label-width="150px">
          <el-select :disabled="disabled" v-model="formData.brandId" placeholder="请选择商品品牌">
            <el-option v-for="item in authBrandOptions" :key="item.value" :label="item.brandName" :value="item.brandId"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品单位" prop="unit" label-width="150px">
          <el-input :disabled="disabled" v-model="formData.unit"></el-input>
        </el-form-item>
        <el-form-item label="年份" prop="years" label-width="150px">
          <el-select :disabled="disabled" v-model="formData.years" placeholder="请选择年份">
            <el-option v-for="item in yearsOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="季节" prop="season" label-width="150px">
          <el-select :disabled="disabled" v-model="formData.season" placeholder="请选择季节">
            <el-option v-for="item in seasonOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="税率（%）" prop="rate" label-width="150px">
          <el-input :disabled="disabled" oninput="if(value>16)value=16;value=value.replace(/[^\d]/g,'')" v-model="formData.rate"></el-input>
        </el-form-item>
        <div class="title">
          销售信息
        </div>
        <el-form-item label="是否启用规格" label-width="150px">
          <el-radio-group :disabled="disabled" v-model="isEnableSpec" @change="enableSpec">
            <el-radio :label="0">不启用</el-radio>
            <el-radio :label="1">启用</el-radio>
          </el-radio-group>
        </el-form-item>
        <div class="sku-table">
          <el-button v-show="isEnableSpec" size="small" class="add-sku-btn" @click="addSku">添加sku</el-button>
          <el-table :data="formData.goodsSkuDTOList" style="width: 100%" border>
            <el-table-column label="图片">
              <template slot-scope="scope">
                <el-form-item :prop="'goodsSkuDTOList.' + scope.$index + '.goodsPic'" :rules="formRules.goodsPic">
                  <el-upload
                    :disabled="disabled"
                    class="avatar-uploader"
                    :action="upladUrl"
                    :show-file-list="false"
                    :on-success="(response, file, fileList) => skuPicHandle(scope.row, response, file, fileList)"
                    :before-upload="beforeUpload"
                  >
                    <el-image v-if="scope.row.goodsPic" :src="scope.row.goodsPic" class="sku-avatar"></el-image>
                    <i v-else class="el-icon-plus sku-avatar-uploader-icon"></i>
                  </el-upload>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="颜色">
              <template slot-scope="scope">
                <el-form-item :prop="'goodsSkuDTOList.' + scope.$index + '.colorAttr'" :rules="formRules.colorAttr">
                  <el-select class="el-input__inner2" :disabled="disabled" @change="searchColor" v-model="scope.row.colorAttr" filterable placeholder="请选择颜色">
                    <el-option v-for="item in colorAttrObj.colorOptions" :key="item.colorCode" :label="item.colorAttr" :value="{ scope: scope.row, value: item.colorCode, label: item.colorAttr }">
                    </el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="规格">
              <template slot-scope="scope">
                <el-form-item :prop="'goodsSkuDTOList.' + scope.$index + '.specAttr'" :rules="formRules.specAttr">
                  <el-select class="el-input__inner2" :disabled="disabled" @change="searchSpec" v-model="scope.row.specAttr" filterable placeholder="请选择颜色">
                    <el-option v-for="item in specAttrObj.specOptions" :key="item.specCode" :label="item.specAttr" :value="{ scope: scope.row, value: item.specCode, label: item.specAttr }">
                    </el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="商家sku编码">
              <template slot-scope="scope">
                <el-form-item :prop="'goodsSkuDTOList.' + scope.$index + '.merSkulNo'" :rules="formRules.merSkulNo">
                  <el-input class="el-input__inner2" :disabled="disabled" maxlength="40" v-model="scope.row.merSkulNo"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="平台SKU编码">
              <template slot-scope="scope">
                <el-form-item>
                  <el-input class="el-input__inner2" placeholder="平台自动生成" :disabled="true" v-model="scope.row.platSkulNo"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="供货价">
              <template slot-scope="scope">
                <el-form-item :prop="'goodsSkuDTOList.' + scope.$index + '.supplyPrice'" :rules="formRules.supplyPrice">
                  <el-input
                    class="el-input__inner2"
                    type="number"
                    :disabled="disabled"
                    v-model="scope.row.supplyPrice"
                    onkeyup="var p2 = parseFloat(value).toFixed(2);value = p2>=0?(/\.0?$/.test(value)?value:p2.replace(/0$/,'').replace(/\.0$/,'')):''"
                    onblur="value = value.replace(/\.0*$/,'')"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="建议售价">
              <template slot-scope="scope">
                <el-form-item :prop="'goodsSkuDTOList.' + scope.$index + '.salePrice'" :rules="formRules.salePrice">
                  <el-input
                    class="el-input__inner2"
                    type="number"
                    :disabled="disabled"
                    v-model="scope.row.salePrice"
                    onkeyup="var p2 = parseFloat(value).toFixed(2);value = p2>=0?(/\.0?$/.test(value)?value:p2.replace(/0$/,'').replace(/\.0$/,'')):''"
                    onblur="value = value.replace(/\.0*$/,'')"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="50">
              <template slot-scope="scope">
                <i v-if="scope.$index != 0 && scope.row.platSkulNo == null" class="el-icon-delete" @click="deleteSku(scope.$index)"></i>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <el-form-item label="市场价（元）" prop="marketPrice" label-width="150px">
          <el-input
            :disabled="disabled"
            onkeyup="var p2 = parseFloat(value).toFixed(2);value = p2>=0?(/\.0?$/.test(value)?value:p2.replace(/0$/,'').replace(/\.0$/,'')):''"
            onblur="value = value.replace(/\.0*$/,'')"
            maxlength="8"
            v-model="formData.marketPrice"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注：" prop="remark" label-width="150px">
          <el-input :disabled="disabled" maxlength="100" v-model="formData.remark"></el-input>
        </el-form-item>
        <div class="title">
          图文详情
        </div>
        <el-form-item label="商品主图" prop="mainPic" label-width="150px">
          <el-upload
            :disabled="disabled"
            class="avatar-uploader"
            :action="upladUrl"
            :show-file-list="false"
            :on-success="mainPicHandle"
            :before-upload="beforeUpload"
          >
            <el-image v-if="formData.mainPic" :src="formData.mainPic" class="avatar"></el-image>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="封面图" prop="coverPic" label-width="150px">
          <el-upload
            :disabled="disabled"
            class="avatar-uploader"
            :action="upladUrl"
            :show-file-list="false"
            :on-success="coverPicHandle"
            :before-upload="beforeUpload"
          >
            <el-image v-if="formData.coverPic" :src="formData.coverPic" class="avatar"></el-image>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="商品图片" prop="goodsPicSet" label-width="150px">
          <el-upload
            :disabled="disabled"
            :action="upladUrl"
            :file-list="fileLists.dialogImageUrl"
            list-type="picture-card"
            :on-success="goodsPicSetHandle"
            :auto-upload="true"
          >
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{ file }">
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
              <span class="el-upload-list__item-actions">
                <!-- <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleDownload(file)">
                  <i class="el-icon-download"></i>
                </span> -->
                <span v-if="!disabled" class="el-upload-list__item-delete" @click="goodsPicSetDelete(file)">
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="fileLists.dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>

        <el-form-item label="商品透明背景图" prop="backgroundPic" label-width="150px">
          <el-upload class="avatar-uploader" :action="upladUrl" :show-file-list="false" :on-success="backgroundPicHandle" :before-upload="beforeUpload">
            <el-image v-if="formData.backgroundPic" :src="formData.backgroundPic" class="avatar"></el-image>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="商品视频" prop="goodsVideo" label-width="150px">
          <el-upload
            class="upload"
            :disabled="disabled"
            :action="upladUrl"
            :file-list="fileLists.goodsVideo"
            :on-success="goodsVideoHandle"
            :before-upload="beforeUploadVedio"
            :on-remove="goodsVideoRemove"
            :on-preview="previewFile"
            accept=".mp4,.avi,.rmvb,.mpg,.mpeg,.mpe,.wmv,.mkv"
            :multiple="false"
            :limit="1"
            :on-exceed="handleExceed"
          >
            <el-button size="small" type="primary">上传文件</el-button>
            <div slot="tip" class="el-upload__tip">加盖公司公章，支持.mp4,.avi,.rmvb,.mpg,.mpeg,.mpe,.wmv,.mkv格式文件，大小需小于20M</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="商品详情" prop="goodsDescription" label-width="150px">
          <!-- <tinymce-editor v-model="formData.goodsDescription" @blur="clearValidInfo" /> -->
        </el-form-item>
      </el-form>
    </div>
    <div>
      <el-dialog title="颜色" :visible.sync="showQueryDialog">
        <el-select filterable placeholder="请选择颜色">
          <el-option v-for="item in colorAttrObj.colorOptions" :key="item.colorCode" :label="item.colorAttr" :value="{ value: item.colorCode, label: item.colorAttr }"> </el-option>
        </el-select>
      </el-dialog>
    </div>
  </div>
</template>
<script>
// import { debounce } from '@/utils/config'
// import tinymceEditor from '@/components/tinymceEditor/v1/index'
import { mpGoodsDetailByGoodsId, backGoodsCategory } from '@/api/merchantsys/goods'
import { selectAuthBrand, getSpecGroup } from '@/api/merchantsys/config'
export default {
  name: 'goodsDetail',
  components: {
    // tinymceEditor
  },
  metaInfo() {
    return {
      titleTemplate: '入驻 - %s'
    }
  },
  computed: {},
  data() {
    var checkUnit = (rule, value, callback) => {
      const reg = new RegExp('[\\u4E00-\\u9FFF]+', 'g')
      if (!reg.test(value)) {
        return callback(new Error('请输入汉字'))
      }
      return callback()
    }

    var checkOutSerialNo = (rule, value, callback) => {
      const reg = new RegExp(/^[0-9A-Za-z]{0,30}$/, 'g')
      if (!reg.test(value)) {
        return callback(new Error('格式为数字或字母'))
      }
      return callback()
    }

    return {
      pageLoaded: false,
      //显示规格查询
      showQueryDialog: false,
      //规格列表
      specData: [],
      //颜色
      colorAttrObj: { attrId: null, attrGroupId: null, colorOptions: [] },
      specAttrObj: { attrId: null, attrGroupId: null, specOptions: [] },
      isEnableSpec: 0,
      dialogImageUrl: [],
      dialogVisible: false,
      disabled: true,
      props: {
        expandTrigger: 'click',
        emitPath: true,
        lazy: true,
        lazyLoad: this.lazyLoad
      },
      showEditBtn: false,
      //年份
      yearsOptions: [],
      //季节
      seasonOptions: [
        {
          value: '四季',
          label: '四季'
        },
        {
          value: '春季',
          label: '春季'
        },
        {
          value: '夏季',
          label: '夏季'
        },
        {
          value: '秋季',
          label: '秋季'
        },
        {
          value: '冬季',
          label: '冬季'
        }
      ],
      url: 'https://oss-uat.bisinuolan.cn/default-1603939412574-1cff7232c9304b2babb9fbede88948c3.png',
      fileLists: {
        dialogImageUrl: [],
        goodsPicSet: [],
        goodsVideo: []
      },
      loading: false,
      formRules: {
        cateId: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
        name: [
          { required: true, message: '商品名称不能为空', trigger: 'blur' },
          { max: 50, message: '商品名称最大字符100', trigger: 'blur' }
        ],
        outSerialNo: [
          { required: true, message: '商家商品编码不能为空', trigger: 'blur' },
          { max: 30, message: '商家商品编码最大字符30', trigger: 'blur' },
          { validator: checkOutSerialNo, trigger: 'blur' }
        ],
        brandId: [{ required: true, message: '请选择商品品牌', trigger: 'change' }],
        unit: [
          { required: true, message: '商品单位不能为空', trigger: 'blur' },
          { max: 10, message: '商品单位最大字符10', trigger: 'blur' },
          { required: true, validator: checkUnit, trigger: 'blur' }
        ],
        years: [{ required: true, message: '请选择年份', trigger: 'change' }],
        season: [{ required: true, message: '请选择季节', trigger: 'change' }],
        rate: [{ required: true, message: '税率不能为空', trigger: 'blur' }],
        goodsPic: [{ required: true, message: '图片不能为空', trigger: 'blur' }],
        colorAttr: [{ required: true, message: '请选择颜色', trigger: 'blur' }],
        specAttr: [{ required: true, message: '请选择规格', trigger: 'blur' }],
        merSkulNo: [
          { required: true, message: 'sku编码不能为空', trigger: 'blur' },
          { max: 40, message: 'sku编码最大字符40', trigger: 'blur' }
        ],
        supplyPrice: [{ required: true, message: '供货价不能为空', trigger: 'blur' }],
        salePrice: [{ required: true, message: '建议售价不能为空', trigger: 'blur' }],
        marketPrice: [{ required: true, message: '市场价不能为空', trigger: 'blur' }],
        remark: [{ max: 100, message: '联系人最大字符100', trigger: 'blur' }],
        //商品主图
        mainPic: [{ required: true, message: '请上传商品主图', trigger: 'change' }],
        //商品封面图
        coverPic: [{ required: true, message: '请上传商品封面图', trigger: 'change' }],
        //商品图片集
        goodsPicSet: [{ required: true, message: '请上传商品图片', trigger: 'change' }],
        //透明背景图
        backgroundPic: [{ required: true, message: '请上传商品透明背景图', trigger: 'change' }],
        //商品详情
        goodsDescription: [{ required: true, message: '商品详情不能为空', trigger: 'blur' }]
      },
      labelPosition: 'right',
      formData: {
        id: null,
        accountId: null,
        name: null,
        outSerialNo: null,
        cateId: null,
        cateArr: [],
        brandId: null,
        unit: null,
        years: null,
        season: null,
        rate: null,
        goodsSkuDTOList: [
          {
            colorAttr: '均色',
            colorAttrCode: '0000',
            goodsPic: null,
            merSkulNo: null,
            platSkulNo: null,
            salePrice: null,
            specAttr: '均码',
            specAttrCode: '999',
            supplyCode: null,
            supplyPrice: null,
            upShelf: null
          }
        ],
        marketPrice: null,
        remark: null,
        mainPic: null,
        coverPic: null,
        goodsPicSet: null,
        goodsVideo: null,
        goodsDescription: null,
        backgroundPic: null
      },
      backCategory: [],
      authBrandOptions: [],
      cateOptions: []
    }
  },
  created() {
    //初始化年份
    this.initYears()
    
    //初始化数据
    this.loadInitData()
  },
  methods: {
    initYears() {
      let year = new Date().getFullYear()
      for (let i = 0; i < 10; i++) {
        this.yearsOptions.push({ label: year - i, value: year - i })
      }
    },
    searchColor(params) {
      const { scope, label, value } = params
      scope.colorAttr = label
      scope.colorAttrCode = value
    },
    searchSpec(params) {
      const { scope, label, value } = params
      scope.specAttr = label
      scope.specAttrCode = value
    },
    enableSpec() {
      console.log(this.isEnableSpec)
    },
    clearValidInfo() {
      this.$refs.formData.validateField('goodsDescription', valid => {
        if (!valid) {
          return
        }
      })
    },
    deleteSku(index) {
      if (index == 0) {
        this.$message({ message: '至少保留一个sku必填项', type: 'error', duration: 3 * 1000 })
        return
      }
      this.formData.goodsSkuDTOList.splice(index, 1)
    },
    addSku() {
      this.formData.goodsSkuDTOList.push({
        colorAttr: null,
        colorAttrCode: null,
        goodsPic: null,
        merSkulNo: null,
        platSkulNo: null,
        salePrice: null,
        specAttr: null,
        specAttrCode: null,
        supplyCode: null,
        supplyPrice: null,
        upShelf: null
      })
    },
    backList() {
      this.$router.push({ path: '/goods/list' })
    },
    checkSkuSpec(skuList) {
      let flag = false
      for (let i = 0; i < skuList.length; i++) {
        for (let j = i + 1; j < skuList.length; j++) {
          if (skuList[i].colorAttrCode == skuList[j].colorAttrCode && skuList[i].specAttrCode == skuList[j].specAttrCode) {
            flag = true
            break
          }
        }
        if (flag) {
          break
        }
      }
      return flag
    },
    skuPicHandle(skuItem, res) {
      skuItem.goodsPic = res.filePath
    },
    //商品主图
    mainPicHandle(res, file) {
      console.log(file)
      const { filePath } = res
      this.formData.mainPic = filePath
    },
    //封面图
    coverPicHandle(res, file) {
      console.log(file)
      const { filePath } = res
      this.formData.coverPic = filePath
    },
    //商品透明背景图
    backgroundPicHandle(res, file) {
      console.log(file)
      const { filePath } = res
      this.formData.backgroundPic = filePath
    },
    //商品视频
    goodsVideoHandle(res, file) {
      console.log(file)
      const { filePath } = res
      this.formData.goodsVideo = filePath
      this.fileLists.goodsVideo.push({ name: file.name, url: filePath })
    },
    goodsVideoRemove() {
      this.formData.goodsVideo = null
      this.fileLists.goodsVideo = []
    },
    //商品图片
    goodsPicSetHandle(res, file) {
      const fileName = file.raw.name
      const { filePath } = res
      this.fileLists.dialogImageUrl.push({ name: fileName, url: filePath })
      let arr = []
      this.fileLists.dialogImageUrl.forEach(element => {
        arr.push(element.url)
      })
      this.formData.goodsPicSet = arr.join(';')
    },
    //删除商品图片
    goodsPicSetDelete(file) {
      this.fileLists.dialogImageUrl.forEach((element, index) => {
        if (file.url == element.url) {
          this.fileLists.dialogImageUrl.splice(index, 1)
          if (this.fileLists.dialogImageUrl.length > 0) {
            this.formData.goodsPicSet = this.fileLists.dialogImageUrl.join(';')
          } else {
            this.formData.goodsPicSet = null
          }
          return
        }
      })
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    beforeUpload(file) {
      const isLegalFormat = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'application/pdf'
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isLegalFormat) {
        this.$message.error('上传文件只支持pdf、png、jpg格式文件')
        return false
      }
      if (!isLt5M) {
        this.$message.error('上传文件大小不能超过 5MB!')
        return false
      }
      return true
    },
    beforeUploadVedio(file) {
      console.log('type', file.type)
      const isLegalFormat =
        file.type === 'video/mp4' ||
        file.type === 'video/avi' ||
        file.type === 'video/rmvb' ||
        file.type === 'video/mpg' ||
        file.type === 'video/mpeg' ||
        file.type === 'video/mpe' ||
        file.type === 'video/wmv' ||
        file.type === 'video/mkv'
      const isLt20M = file.size / 1024 / 1024 < 20
      if (!isLegalFormat) {
        this.$message.error('上传文件只支持mp4,avi,rmvb,mpg,mpeg,mpe,wmv,mkv格式文件')
        return false
      }
      if (!isLt20M) {
        this.$message.error('上传视频大小不能超过 20MB!')
        return false
      }
      return true
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    beforeRemove(file, fileList) {
      console.log(file, fileList)
    },
    searchBlur(params) {
      const { value, label } = params
      this.formData.brandId = value
      this.formData.brandName = label
    },
    //加载商品品牌
    selectAuthBrandOption() {
      selectAuthBrand({account_id: this.formData.accountId}).then(res=>{
        this.authBrandOptions = res.data
      })
    },
    //商品颜色规格
    handleChange(value) {
      this.colorAttrObj.colorOptions = []
      this.specAttrObj.specOptions = []
      //最后一级分类
      this.formData.cateId = value[value.length - 1]
      //完整分类集合
      this.formData.cateArr = value
      //获取关联属性组
      getSpecGroup({ back_cate_id: this.formData.cateId }).then(res => {
        if (!res.success && res.data.length > 0) {
          return
        }
        let specArr = res.data
        specArr.forEach(element => {
          if (element.name == '颜色') {
            this.colorAttrObj.attrId = element.id
            this.colorAttrObj.attrGroupId = element.attrGroupId
            element.inputs.forEach(item => {
              let colorOption = item.split(':')
              let colorCode = colorOption[0]
              let colorAttr = colorOption[1]
              this.colorAttrObj.colorOptions.push({ colorCode: colorCode, colorAttr: colorAttr })
            })
          }
          if (element.name == '规格') {
            this.specAttrObj.attrId = element.id
            this.specAttrObj.attrGroupId = element.attrGroupId
            element.inputs.forEach(item => {
              let specOption = item.split(':')
              let specCode = specOption[0]
              let specAttr = specOption[1]
              this.specAttrObj.specOptions.push({ specCode: specCode, specAttr: specAttr })
            })
          }
        })
      })
    },
    //详情
    loadInitData() {
      //this.formData.accountId = this.$store.getters.account.accountInfoDTO.accountId
      if (!this.$route.params.id) {
        this.disabled = false
        this.pageLoaded = true
        return
      }
      const res = mpGoodsDetailByGoodsId({ goodsId: this.$route.params.id }).then(res=>{
        this.formData = res.data
        //加载商品品牌
        this.selectAuthBrandOption()
        //加载一级分类
        this.loadCateOptions()
        //加载关联规格
        this.handleChange(this.formData.cateArr)
        if (this.formData.goodsPicSet) {
          let arr = this.formData.goodsPicSet.split(';') || []
          arr.forEach((item, index) => {
            this.fileLists.dialogImageUrl.push({ name: '商品图片' + ++index, url: item })
          })
        }
        if (this.formData.goodsVideo) {
          this.fileLists.goodsVideo.push({ name: '商品视频' + this.getExtendName(this.formData.goodsVideo), url: this.formData.goodsVideo })
        }
      })
    },
    lazyLoad(node, resolve) {
      this.getData(node, resolve)
    },
    getData(node, resolve) {
      const level = node.level
      const res = backGoodsCategory({ parent_cate_id: node.value }).then(res=>{
          var result
        if (level === 0) {
          this.backCategory = res.data
          result = res.data
          result.forEach(item => {
            item.value = item.catId
            item.label = item.name
          })
        }
        if (level === 1) {
          result = res.data
          result.forEach(item => {
            item.value = item.catId
            item.label = item.name
          })
        }
        if (level === 2) {
          result = res.data
          result.forEach(item => {
            item.value = item.catId
            item.label = item.name
            //这句代码表示当点击最后一级的时候 label后面不会转圈圈 并把相关值赋值到选择器上
            item.leaf = level >= 2
          })
        }
        resolve(result)
      })
    },
    loadCateOptions() {
      //回显分类数据 this.formData.cateArr为['一级分类','二级分类','三级分类']
      let cateObj = { value: null, label: null }
      backGoodsCategory().then(res => {
        let ele = res.data
        ele.forEach(element => {
          if (element.catId == this.formData.cateArr[0]) {
            cateObj = { value: element.catId, label: element.name, children: [] }
            backGoodsCategory({ parent_cate_id: this.formData.cateArr[0] }).then(item => {
              let secondRes = item.data
              secondRes.forEach(sec => {
                if (sec.catId == this.formData.cateArr[1]) {
                  let secondCateObj = { value: sec.catId, label: sec.name, children: [] }
                  backGoodsCategory({ parent_cate_id: this.formData.cateArr[1] }).then(thir => {
                    let thirRes = thir.data
                    thirRes.forEach(lastCate => {
                      if (lastCate.catId == this.formData.cateArr[2]) {
                        let lastCateObj = { value: lastCate.catId, label: lastCate.name }
                        secondCateObj.children.push(lastCateObj)
                        cateObj.children.push(secondCateObj)
                        this.pageLoaded = true
                        // this.cateOptions.push(cateObj)
                      }
                    })
                  })
                }
              })
            })
          }
        })
      })
    },
    previewFile(file) {
      window.open(file.url)
    },
    getExtendName(url) {
      return url.substring(url.lastIndexOf('.'))
    }
  }
}
</script>

<style lang="scss">
.goods-base-detail-container{
  padding:20px;
    .register-main{
      .operate-btn{
        margin-bottom: 10px;
      }
      .title{
        font-size: 18px;
        color: black;
        font-weight: bold;
        line-height: 38px;
        margin-bottom: 10px;
      }
      .el-cascader{
        margin-bottom: 10px;
      }
      .sku-table{
        margin-bottom: 10px;
        .add-sku-btn{
          width: 100%;
          border: 1px dashed gray;
          margin-bottom:10px;
        }
        .el-icon-delete{
          margin-left: 6px;
        }
      }
      .el-form-item{
        .next-btn{
          width: 150px;
        }
        .el-input{
          width: 420px;
        }
        .upload{
          width: 450px;
        }
      }
    }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    margin-left: -15px;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    height: 150px;
    line-height: 150px;
    text-align: center;
  }
  .avatar {
    width: 150px;
    height: 150px;
    display: block;
  }
  .sku-avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .sku-avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
  .el-input__inner2{
    margin-left: -65px;
    width: 150px;
  }
}

</style>
